package com.payment.ktb.activity.main4;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;

import com.android.volley.VolleyError;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.BaseActivity;
import com.payment.ktb.activity.MainActivity;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.FileUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.LogUtil;
import com.payment.ktb.utils.PhtotUtils;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.ToastUtils;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by admin on 2017/8/29.
 */

public class PortraitActivity extends BaseActivity {

    File file;
    //版本比较：是否是4.4及以上版本
    static boolean mIsKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    Activity thisActivity;
    int takePhotoRequestCode = 5;
    int pickPhotoRequestCode = 6;


    @BindView(R.id.iv_portrait_content)
    ImageView iv_portrait_content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_portrait);
        ButterKnife.bind(this);
        file = new File(Environment.getExternalStorageDirectory(), SharedPreferencesUtils.getString(ConstantsUser.phone) + "avatar.png");

        thisActivity = this;

    }


    @OnClick({R.id.iv_portrait_left,R.id.iv_portrait_right})
    public void clickEvent(View view){


        switch (view.getId()){

            case R.id.iv_portrait_left:
                finish();
                break;


            case R.id.iv_portrait_right:
                setAvatar();
                break;


        }

    }




    /**
     *
     */
    private void setAvatar() {


        final String[] stringItems = {"拍照", "从手机相册选择","保存照片"};
        final ActionSheetDialog dialog = new ActionSheetDialog(mContext, stringItems, null);
        dialog.isTitleShow(false).show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (position == 0) {
                    PhtotUtils.takePhoto(thisActivity, file, takePhotoRequestCode);
                } else if (position == 1){
                    PhtotUtils.pickPhoto(thisActivity,pickPhotoRequestCode);
                }else if (position == 2) {
                    iv_portrait_content.setDrawingCacheEnabled(true);
                    iv_portrait_content.buildDrawingCache();
                    Bitmap bitmap = iv_portrait_content.getDrawingCache();
                    if (bitmap != null) {
                        ToastUtils.showToast("保存成功！");
                        Bitmap b = PhtotUtils.compressImage(bitmap);
                        savePic(b);
                    } else {
                        ToastUtils.showToast("保存失败！");
                    }
                    view.destroyDrawingCache();

                }
                dialog.dismiss();
            }
        });
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == takePhotoRequestCode && resultCode == RESULT_OK) {

            // 对拍照之后的图片进行压缩。
            Bitmap bitmap = PhtotUtils.compressBySize(file.getPath(),2560, 1440);
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;// 不去真的解析图片，只是获取图片的头部信息，包含宽高等；
            Bitmap bitmapTemp = BitmapFactory.decodeFile(file.getPath(),opts);
            // 设置好缩放比例后，加载图片进内容；
            opts.inJustDecodeBounds = false;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            while (baos.toByteArray().length / 1024>200) {
                bitmap = null;
                bitmap = BitmapFactory.decodeFile(file.getPath(), opts);
                opts.inSampleSize = opts.inSampleSize + 5;
                baos.reset();//重置baos即清空baos ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
            }

            //显示图片
            final Bitmap b = PhtotUtils.compressImage(bitmap);

            ByteArrayOutputStream byos = new ByteArrayOutputStream();
            b.compress(Bitmap.CompressFormat.JPEG,100,byos);
            try {
                FileOutputStream f = new FileOutputStream(file);
                try {
                    f.write(byos.toByteArray());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            iv_portrait_content.setImageBitmap(b);

            progressDialogUtils.showProgress("正在上传照片...");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    uploadFile(b, "Other");
                }
            }).start();


        } else if (requestCode == pickPhotoRequestCode && resultCode == RESULT_OK) {
            String pickPhotoPath = null;
            if (mIsKitKat) {
                pickPhotoPath = PhtotUtils.getPickPhotoPathAfterKitKat(mContext, data.getData());
            } else {
                pickPhotoPath = PhtotUtils.handleUri(this,data);
            }


            // 对拍照之后的图片进行压缩。
            Bitmap bitmap = PhtotUtils.compressBySize(pickPhotoPath,2560, 1440);
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;// 不去真的解析图片，只是获取图片的头部信息，包含宽高等；
            Bitmap bitmapTemp = BitmapFactory.decodeFile(pickPhotoPath,opts);
            // 设置好缩放比例后，加载图片进内容；
            opts.inJustDecodeBounds = false;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            while (baos.toByteArray().length / 1024>200) {
                bitmap = null;
                bitmap = BitmapFactory.decodeFile(pickPhotoPath, opts);
                opts.inSampleSize = opts.inSampleSize + 5;
                baos.reset();//重置baos即清空baos ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
            }


            //显示图片
            final Bitmap b = PhtotUtils.compressImage(bitmap);

            iv_portrait_content.setImageBitmap(b);
            ByteArrayOutputStream byos = new ByteArrayOutputStream();
            b.compress(Bitmap.CompressFormat.JPEG,100,byos);
            try {
                FileOutputStream f = new FileOutputStream(file);
                try {
                    f.write(byos.toByteArray());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            progressDialogUtils.showProgress("正在上传照片...");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    uploadFile(b, "Other");
                }
            }).start();


        }

    }



    /**
     * 截取当前屏幕，并跳转到微信
     */
    private void savePic(Bitmap bitmap) {

        if (bitmap != null) {
            //String filePath = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "title", "description");
            //sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(filePath))));
            FileUtils.saveImageToGallery(mContext,bitmap);
            ToastUtils.showToast("保存成功！");
        } else {
            ToastUtils.showToast("保存失败！");
        }
    }






    @Override
    protected void onResume() {
        super.onResume();
        file = new File(Environment.getExternalStorageDirectory(), SharedPreferencesUtils.getString(ConstantsUser.phone) + "avatar.png");

        if (!TextUtils.isEmpty( SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.picHeader))){
            Picasso.with(mContext).load(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.picHeader)).into(iv_portrait_content);
        }else if (file != null && file.exists()) {
            iv_portrait_content.setImageBitmap(BitmapFactory.decodeFile(file.getPath()));
        }
    }




    /**
     * 上传照片
     */
    private void uploadFile(Bitmap bitmap, final String type) {


        //将图片写到out中
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        String fileBase64 = Base64.encodeToString(out.toByteArray(), 0, out.toByteArray().length, Base64.DEFAULT);
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //将图片的字节流数据加密成base64字符输出
        fileBase64 = "data:image/png;base64," + fileBase64;

        //将参数放入map中
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("fileBase64", fileBase64);
        map.put("type", type);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.FileUploadState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();

                try {
                    JSONObject jsonObject = new JSONObject(response);

                    SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.picHeader, jsonObject.optString("httpPath"));

                    submit();





                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });
    }





    private void submit() {

        //构造传输参数
        Map<String, String> map = new HashMap<String,String>();
        map.put("picHeader", SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.picHeader));
        map.put("userNick",SharedPreferencesUtils.getString(ConstantsUser.userNick));

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.UserBaseDetailEditState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();
                ToastUtils.showToast("照片上传成功！");
            }
            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });
    }




}
